package com.sanyue.codingsettlement.service.impl;

import java.util.Date;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.errorprone.annotations.concurrent.LazyInit;
import com.sanyue.codingsettlement.common.ErrorCode;
import com.sanyue.codingsettlement.constant.CommonConstant;
import com.sanyue.codingsettlement.exception.ThrowUtils;
import com.sanyue.codingsettlement.mapper.TeamMapper;
import com.sanyue.codingsettlement.mapper.UserTeamMapper;
import com.sanyue.codingsettlement.model.dto.team.TeamQueryRequest;
import com.sanyue.codingsettlement.model.entity.*;
import com.sanyue.codingsettlement.model.enums.TeamStatusEnum;
import com.sanyue.codingsettlement.model.vo.TeamVO;
import com.sanyue.codingsettlement.model.vo.UserVO;
import com.sanyue.codingsettlement.service.TeamService;
import com.sanyue.codingsettlement.service.UserService;
import com.sanyue.codingsettlement.service.UserTeamService;
import com.sanyue.codingsettlement.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍表服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService {

    @Resource
    private UserService userService;


    @Resource
    @Lazy
    private UserTeamService userTeamService;

    @Resource
    private UserTeamMapper userTeamMapper;

    /**
     * 校验数据
     *
     * @param team
     * @param add  对创建的数据进行校验
     */
    @Override
    public void validTeam(Team team, boolean add) {
        ThrowUtils.throwIf(team == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String title = team.getTitle();
        String description = team.getDescription();
        String password = team.getPassword();
        String status = team.getStatus();
        Integer maxNumber = team.getMaxNumber();
        Date expireTime = team.getExpireTime();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(TeamStatusEnum.getEnumByValue(status) == null, ErrorCode.PARAMS_ERROR, "队伍状态异常");
            ThrowUtils.throwIf(maxNumber == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(expireTime == null, ErrorCode.PARAMS_ERROR);

        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(title)) {
            ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(description)) {
            ThrowUtils.throwIf(description.length() > 200, ErrorCode.PARAMS_ERROR, "描述过长");
        }
        if (StringUtils.isNotBlank(password)) {
            ThrowUtils.throwIf(password.length() > 8, ErrorCode.PARAMS_ERROR, "密码");
        }
        if (maxNumber != null) {
            ThrowUtils.throwIf(maxNumber > 10, ErrorCode.PARAMS_ERROR, "队伍人数最多为10人");
        }
        if(TeamStatusEnum.ENCRYPT.getValue().equals(status)){
            ThrowUtils.throwIf(StringUtils.isBlank(password), ErrorCode.PARAMS_ERROR,"加密房间必须有密码");
        }
    }

    /**
     * 获取查询条件
     *
     * @param teamQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Team> getQueryWrapper(TeamQueryRequest teamQueryRequest) {


        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        if (teamQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = teamQueryRequest.getId();
        String title = teamQueryRequest.getTitle();
        String description = teamQueryRequest.getDescription();
        List<String> tagList = teamQueryRequest.getTagList();
        String status = teamQueryRequest.getStatus();
        Long userId = teamQueryRequest.getUserId();
        Date expireTime = teamQueryRequest.getExpireTime();
        String sortField = teamQueryRequest.getSortField();
        String sortOrder = teamQueryRequest.getSortOrder();
        String searchText = teamQueryRequest.getSearchText();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("description", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 在队伍截止时间之前
        queryWrapper.lt(expireTime != null,"expireTime",expireTime);
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取队伍表封装
     *
     * @param team
     * @param request
     * @return
     */
    @Override
    public TeamVO getTeamVO(Team team, HttpServletRequest request) {
        // 对象转封装类
        TeamVO teamVO = TeamVO.objToVo(team);
        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = team.getUserId();
        User user = null;
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        Long teamId = team.getId();
        if (userId != null && userId > 0) {
            user = userService.getById(userId);

            Long loginUserId = userService.getLoginUser(request).getId();
            queryWrapper.eq("teamId",teamId);
            queryWrapper.eq("userId",loginUserId);
            long count = userTeamService.count();
            if(count >= 0){
                teamVO.setIsJoined(true);
            }
        }
        UserVO userVO = userService.getUserVO(user);
        teamVO.setUser(userVO);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teamId",teamId);
        long count = userTeamService.count();
        teamVO.setHasJoinedNumber(count);
        // endregion

        return teamVO;
    }

    /**
     * 分页获取队伍表封装
     *
     * @param teamPage
     * @param request
     * @return
     */
    @Override
    public Page<TeamVO> getTeamVOPage(Page<Team> teamPage, HttpServletRequest request) {
        List<Team> teamList = teamPage.getRecords();
        Page<TeamVO> teamVOPage = new Page<>(teamPage.getCurrent(), teamPage.getSize(), teamPage.getTotal());
        if (CollUtil.isEmpty(teamList)) {
            return teamVOPage;
        }
        // 对象列表 => 封装对象列表
        List<TeamVO> teamVOList = teamList.stream().map(team -> {
            return TeamVO.objToVo(team);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = teamList.stream().map(Team::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 2.查询队伍加入人员数量

        //拿出所有的数据的ID
        Map<Long, Long> hasJoinedNumberMap = new HashMap<>();
        Set<Long> teamIdSet = teamList.stream().map(Team::getId).collect(Collectors.toSet());
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("teamId", teamIdSet);
        //找出所有展示的队伍
        List<UserTeam> list = userTeamMapper.selectList(queryWrapper);
        //将所有的队伍ID放入map中
        list.forEach(userTeam ->{
            QueryWrapper<UserTeam> qw = new QueryWrapper<>();
            qw.eq("teamId",userTeam.getTeamId());
            long count = userTeamService.count(queryWrapper);
            hasJoinedNumberMap.put(userTeam.getTeamId(),count);
        });



        // 3. 已登录，获取用户队伍状态
        Map<Long, Boolean> IsJoinedMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {

            loginUser = userService.getLoginUser(request);
            // 获取点赞
            QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
            userTeamQueryWrapper.in("teamId", teamIdSet);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            // 找出所有自己点赞的帖子
            List<UserTeam> userTeamList = userTeamMapper.selectList(userTeamQueryWrapper);
            // 将所有自己点赞过的帖子的值设置为true
            userTeamList.forEach(userTeam -> IsJoinedMap.put(userTeam.getTeamId(), true));
        }

        // 填充信息
        teamVOList.forEach(teamVO -> {
            Long userId = teamVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            teamVO.setUser(userService.getUserVO(user));
            teamVO.setIsJoined(IsJoinedMap.getOrDefault(teamVO.getId(), false));
            teamVO.setHasJoinedNumber(hasJoinedNumberMap.getOrDefault(teamVO.getId(), 0L));
        });
        // endregion
        teamVOPage.setRecords(teamVOList);
        return teamVOPage;
    }

}
